package com.naodong.shenluntiku.util;

import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.BackgroundColorSpan;
import android.text.style.BulletSpan;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.view.View;
import android.widget.TextView;

import com.naodong.shenluntiku.mvp.view.activity.WebViewActivityAutoBundle;

import org.xml.sax.XMLReader;

import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hujie on 17/3/10.
 */

public class HtmlUtil {

    private static final Pattern linkUrlPattern = Pattern
            .compile("([hH][tT][tT][pP][sS]?)://[a-zA-Z0-9\\-_]+(\\.[a-zA-Z0-9\\-_]+)+([a-zA-Z0-9_\\-\\.,@?^=%&amp;:/~\\+#]*[a-zA-Z0-9_\\-@?^=%&amp;/~\\+#])?");


    public static Spannable fromHtml(Context context, String source) {

        Spanned spanned = Html.fromHtml(source);
        Spannable spannable = new Spannable.Factory().newSpannable(spanned);
        try {
            URLSpan[] urlSpans = spannable.getSpans(0, spannable.length(), URLSpan.class);
            if (urlSpans != null && urlSpans.length > 0) {
                for (URLSpan urlSpan : urlSpans) {
                    int start = spannable.getSpanStart(urlSpan);
                    int end = spannable.getSpanEnd(urlSpan);
                    int flag = spannable.getSpanFlags(urlSpan);

                    String url = urlSpan.getURL();
                    ClickableSpan span = new ClickableSpan() {
                        @Override
                        public void updateDrawState(TextPaint ds) {
                            super.updateDrawState(ds);
                        }

                        @Override
                        public void onClick(View widget) {
                            // 单击事件处理
                            context.startActivity(WebViewActivityAutoBundle.builder(url).build(context));
                        }
                    };
                    spannable.removeSpan(urlSpan);
                    spannable.setSpan(span, start, end, flag);
                }
            } else {

                Matcher tmatcher = linkUrlPattern.matcher(source);
                while (tmatcher.find()) {
                    String url = tmatcher.group();

                    int start = tmatcher.start();
                    int end = tmatcher.end();

                    ClickableSpan span = new ClickableSpan() {
                        @Override
                        public void updateDrawState(TextPaint ds) {
                            super.updateDrawState(ds);
                        }

                        @Override
                        public void onClick(View widget) {
                            // 单击事件处理
                            context.startActivity(WebViewActivityAutoBundle.builder(url).build(context));
                        }
                    };
                    spannable.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }

            }
        } catch (Exception e) {

        }
        return spannable;


    }

    public static void fromHtml(TextView textView, String html) {



        String text = html; // HTML text to convert
        // Preprocessing phase to set up for HTML.fromHtml(...)
        text = text.replaceAll("<span style=\"(?:color:(#[a-fA-F\\d]{6})?;)?(?:font-family:(.*?);)?(?:font-size:(.*?);)? ?\">(.*?)</span>",
                "<font color=\"$1\" face=\"$2\" size=\"$3\">$4</font>");
        text = text.replaceAll("(?<=<font color=\"#[a-fA-F0-9]{6}\" )face=\"'(.*?)', .*?\"", "face=\"$1\"");
        text = text.replaceAll("(?<=<font color=\"#[a-fA-F0-9]{6}\" )(face=\".*?\" )size=\"xx-small\"", "$1size=\"1\"");
        text = text.replaceAll("(?<=<font color=\"#[a-fA-F0-9]{6}\" )(face=\".*?\" )size=\"x-small\"", "$1size=\"2\"");
        text = text.replaceAll("(?<=<font color=\"#[a-fA-F0-9]{6}\" )(face=\".*?\" )size=\"small\"", "$1size=\"3\"");
        text = text.replaceAll("(?<=<font color=\"#[a-fA-F0-9]{6}\" )(face=\".*?\" )size=\"medium\"", "$1size=\"4\"");
        text = text.replaceAll("(?<=<font color=\"#[a-fA-F0-9]{6}\" )(face=\".*?\" )size=\"large\"", "$1size=\"5\"");
        text = text.replaceAll("(?<=<font color=\"#[a-fA-F0-9]{6}\" )(face=\".*?\" )size=\"x-large\"", "$1size=\"6\"");
        text = text.replaceAll("(?<=<font color=\"#[a-fA-F0-9]{6}\" )(face=\".*?\" )size=\"xx-large\"", "$1size=\"7\"");

        text = text.replaceAll("<span style=\"background-color: #([a-fA-F0-9]{6}).*?>(.*?)</span>", "<_$1>$2</_$1>");

        textView.setText(Html.fromHtml(text,null, new Html.TagHandler() {
            private List<Object> _format_stack = new LinkedList<Object>();

            @Override
            public void handleTag(boolean open_tag, String tag, Editable output, XMLReader xmlReader) {
                if (tag.startsWith("ul"))
                    processBullet(open_tag, output);
                else if (tag.matches(".[a-fA-F0-9]{6}"))
                    processBackgroundColor(open_tag, output, tag.substring(1));
            }

            private void processBullet(boolean open_tag, Editable output) {
                final int length = output.length();
                if (open_tag) {
                    final Object format = new BulletSpan(BulletSpan.STANDARD_GAP_WIDTH);
                    _format_stack.add(format);
                    output.setSpan(format, length, length, Spanned.SPAN_MARK_MARK);
                } else {
                    applySpan(output, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }

            private void processBackgroundColor(boolean open_tag, Editable output, String color) {
                final int length = output.length();
                if (open_tag) {
                    final Object format = new BackgroundColorSpan(Color.parseColor('#' + color));
                    _format_stack.add(format);
                    output.setSpan(format, length, length, Spanned.SPAN_MARK_MARK);
                } else {
                    applySpan(output, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }

            private Object getLast(Editable text, Class kind) {
                @SuppressWarnings("unchecked")
                final Object[] spans = text.getSpans(0, text.length(), kind);

                if (spans.length != 0)
                    for (int i = spans.length; i > 0; i--)
                        if (text.getSpanFlags(spans[i - 1]) == Spannable.SPAN_MARK_MARK)
                            return spans[i - 1];

                return null;
            }

            private void applySpan(Editable output, int length, int flags) {
                if (_format_stack.isEmpty()) return;

                final Object format = _format_stack.remove(0);
                final Object span = getLast(output, format.getClass());
                final int where = output.getSpanStart(span);

                output.removeSpan(span);

                if (where != length)
                    output.setSpan(format, where, length, flags);
            }
        }));

    }


}
